package com.xingda.packing.dmss.task.generate;

import com.xingda.packing.dmss.domain.PackProductionLine;
import com.xingda.packing.dmss.domain.ProductBoxLocation;
import com.xingda.packing.dmss.domain.Wheel;
import com.xingda.packing.dmss.enums.BoxLocationNo;
import com.xingda.packing.dmss.enums.TaskState;
import com.xingda.packing.dmss.rule.RuleUtilsV2;
import com.xingda.packing.dmss.task.ticket.AbstractTaskTicket;
import com.xingda.packing.dmss.task.ticket.PackingTicket;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 抓取位放装箱位
 *
 * @author LEGION
 */
@Order(3)
@Component
public class PackingGenerate implements TaskGenerateService {
    @Resource
    RuleUtilsV2 ruleUtils;

    @Override
    public AbstractTaskTicket generate(PackProductionLine productionLine, int area) {
        if (!productionLine.getRobot().checkCanAssignTaskTicket(area)) {
            return null;
        }
        if (!productionLine.getRobot().canAssignTask(area)) {
            return null;
        }
        if (productionLine.getRobot().isEmpty(area)) {
            return null;
        }
        if (!productionLine.getRobot().checkActionStatus(area)) {
            productionLine.getRobot().createAlarmEvent("当前区域存在未完成任务,已停止机器人,请去后台管理页面:[操作管理-动作操作]查看", area);
            productionLine.setInitRunning(area, false);
            return null;
        }
        Wheel wheel = productionLine.getRobot().getWheel(area);
        for (ProductBoxLocation productBoxLocation : productionLine.getProductArea().getLocationList(area)) {
            if (productBoxLocation.isEmpty()) {
                continue;
            }
            if (productBoxLocation.getProductBox().isFull()) {
                continue;
            }
            if (!productBoxLocation.isPhotoFinish() || productBoxLocation.isPalletComing()) {
                continue;
            }
            if (ruleUtils.canPut(productBoxLocation.getProductBox(), wheel)) {
                PackingTicket ticket = new PackingTicket();
                ticket.setWheel(wheel);
                ticket.setState(TaskState.NEW);
                ticket.setProductBoxLocationNo(BoxLocationNo.getById(productBoxLocation.getLocationNo()).getNo());
                ticket.setArea(area);
                ticket.setTag(productBoxLocation.getLocationNo());
                productionLine.getRobot().createPackingEvent(ticket, area);
                return ticket;
            }
        }
        return null;
    }
}
